<?php

namespace app\index\controller;

use app\gears\validate\GearValidate;
use app\index\common\ApiResponse;
use app\index\common\JwtAuth;
use app\index\model\Order;
use app\index\validate\IndexValidate;
use app\index\validate\DishListValidate;
use app\index\validate\OrderPostValidate;
use think\Db;
use think\db\Query;
use think\Log;

class Index extends Base
{
    public function index()
    {}
    public function login(){
        $data = request()->param();
        $validate = new IndexValidate();
        if (!$validate->scene('login')->check($data)) {
            return ApiResponse::json(300,$validate->getError(),null);
        }
        $userModel = model('User');
        $user = $userModel::get(['userName'=>$data['userName']]);
        if (empty($user)){
            return ApiResponse::json(300,'用户不存在',null);
        }
        if($user->type==2){
            return ApiResponse::json(300,'该账户被禁用，无法登录',null);
        }
        if ($user->password != $data['password']){
            return ApiResponse::json(300,'密码不正确',null);
        }
        $jwtAuth = new JwtAuth();
        $payload = ['userName' => $data['userName'],
            'phone'=>$user->phone,
            'level' => $user->level,
            'userId'=>$user->id];
        $token = $jwtAuth->generateToken($payload);
        $re = ['token'=>$token,'user'=>$user];
        return ApiResponse::json(200,'succeed',$re);
    }
    public function register(){
        $data = request()->param();
        $validate = new IndexValidate();
        if (!$validate->scene('register')->check($data)) {
            return ApiResponse::json(300,$validate->getError(),null);
        }
        $userModel = model('User');
        $user = $userModel->where('userName','=',$data['userName'])->find();
        if (!empty($user)){
            return ApiResponse::json(300,'用户名已存在',null);
        }
        try {
            $userModel->userName = $data['userName'];
            $userModel->password = $data['password'];
            $userModel->level = 3;
            $userModel->phone = $data['phone'];
            if(!empty($data['remark'])){
                $userModel->remark = $data['remark'];
            }
            $userModel->save();
            return ApiResponse::json(200,'成功',null);
        } catch (\Exception $e) {
            return ApiResponse::json(300,$e->getMessage(),null);
        }
    }
    public function orderingPost(){
        $params = request()->param();
        $validate = new IndexValidate();

        $dishList = $params['dishList'];
        if(empty($dishList)){
            return ApiResponse::json(300,'菜品列表不能为空',null);
        }
        foreach ($dishList as $item) {
            if (!$validate->scene('orderPost')->check($item)) {
                return ApiResponse::json(300,$validate->getError(),$item);
            }
        }
        trace($dishList);
        $food = model('DailyFoods');
        try {
            $food->saveAll($dishList);
        } catch (\Exception $e) {
            return ApiResponse::json(300,'error',json_encode($e));
        }
        return ApiResponse::json(200,'提交成功',null);
    }
    public function orderingDelete(){
        $params = request()->param();
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }
        $food = model('DailyFoods');
        $food::get($params['id'])->delete();
        return ApiResponse::json(200,'操作成功',null);
    }
    public function orderList(){
        //获取某一天的菜品
        $dishName = input('dishName'); // 获取dishName参数
        $dateList = input('dateList/a'); // 获取dateList参数（转为数组）
        $where = [];
        if (!empty($dishName)) {
            // 如果dishName不为空，则进行模糊匹配
            $where[] = ['df.dishName','like', '%' . $dishName . '%'];
        }
        if(!$dateList){
            return ApiResponse::json(300,'查询日期不能为空','');
        }
        $page = input('page');
        $pageSize = input('pageSize');
        $params = request()->param();
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        $userId = $payload['userId'];
        $foodModel = model('DailyFoods');
        $list = $foodModel->alias('df')
            ->where($where)->where('df.delete_time', null) // 只获取未删除的菜品
            ->whereTime('df.targetDate', 'between', [$dateList[0], $dateList[1]])
            ->join('UserOrder uo', 'df.id = uo.dishId AND uo.userId = ' . $userId.' AND uo.delete_time IS NULL', 'LEFT') 
            ->order('df.targetDate', 'asc') // 按targetDate字段倒序排序
            ->order('df.timeRange', 'asc')
            ->field('df.*, uo.orderCount, uo.pickUpCount, uo.id AS orderId') 
            ->paginate($pageSize, false, ['page' => $page]);
        return ApiResponse::json(200,'succeed',$list);
    }
    //点单接口
    public function orderDishes() {
        $params = request()->param();
        $orderList = $params['orderList'];
        $totalScore = 0;

        // 实例化模型
        $menuModel = model('DailyFoods');
        $gearModel = model('Gears');
        $userModel = model('User');
        $userOrderModel = model('UserOrder');
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);

        $dishIds = array_column($orderList, 'dishId');
        $hasOrdered = $userOrderModel->where('userId',$payload['userId'])->whereIn('dishId', $dishIds)->count() > 0;
        if($hasOrdered){
            return ApiResponse::json(300, '您已点过该菜品', null);
        }
        $targetUser = $userModel::get(['id' => $payload['userId']]);

        // 预先查询所有菜品和时间段
        $dishes = $menuModel->whereIn('id', $dishIds)->select();
        $dishMap = [];
        foreach ($dishes as $dish) {
            $dishMap[$dish->id] = $dish;
        }

        $gears = $gearModel::all();
        $gearMap = [];
        foreach ($gears as $gear) {
            $gearMap[$gear->value] = $gear;
        }

        $orderList2 = [];
        $isAllowOrderDown = true;

        foreach ($orderList as $dish) {
            $mo = $dishMap[$dish['dishId']];
            $totalScore += $mo->score * $dish['orderCount'];

            $gear = $gearMap[$dish['timeRange']];
            $targetTime = $mo->targetDate . ' ' . $gear->ableEndTime . ':00';
            $currentDate = new \DateTime();
            $targetDate = \DateTime::createFromFormat('Y-m-d H:i:s', $targetTime);

            if ($currentDate > $targetDate) {
                $isAllowOrderDown = false;
                break;
            }

            $text = $gear->ableStartTime . '-' . $gear->ableEndTime;
            $dish['gearTime'] = $text;
            $orderList2[] = $dish;
        }
        if (!$isAllowOrderDown) {
            return ApiResponse::json(300, '已过点餐截止时间', null);
        }
        // 更新用户积分
        $targetUser->score -= $totalScore;
        $targetUser->save();
        $arr = [];
        foreach ($orderList2 as $item) {
            $item['userId'] = $targetUser->id;
            $item['score'] = $totalScore;
            $item['userName'] = $targetUser->userName;
            $arr[] = $item;
        }
        $userOrderModel->saveAll($arr);
        return ApiResponse::json(200, 'succeed', null);
    }

    public function changeScoreByDish() {
        $params = request()->param();
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);

        if ($payload['level'] > 2) {
            return ApiResponse::json(300, '您还不是管理员', null);
        }

        $s1 = input('score');
        $dishId = input('dishId');
        $userOrderModel = model('UserOrder');
        $foodModel = model('DailyFoods');
        $userModel = model('User');

        // 使用数据库事务
        Db::startTrans();
        try {
            // 更新菜品分数
            $food = $foodModel->find($dishId);
            $food->score = $s1;
            $food->save();

            // 获取所有相关订单
            $orderArr = $userOrderModel->where('dishId', $dishId)->select();
            $userIds = [];

            foreach ($orderArr as $item) {
                $userIds[] = $item->userId;
            }
            // 批量获取用户信息
            $users = $userModel->whereIn('id', array_unique($userIds))->select();
            $userMap = [];
            foreach ($users as $user) {
                $userMap[$user->id] = $user;
            }
            $thirtyDaysAgo = strtotime('-30 days');
            $curThirtyDayOrders = model('Order')->where('create_time','>=',$thirtyDaysAgo)
                ->where('dishId', 'neq', '')
                ->where('dishId', 'not null')
                ->select();
            foreach ($orderArr as $item) {
                $targetUser = $userMap[$item->userId];
                $minusScore = floatval($s1) * intval($item->orderCount);
                $targetUser->score -= $minusScore;
                $targetUser->orderType = 1;//已设置金额
                $targetUser->save();
                $item->score = $minusScore;
                $item->save();

                $foundOrder = null;
                foreach ($curThirtyDayOrders as $mo) {
                    if ($mo['dishId'] == $item['dishId'] && $item['userId'] == $mo['userId']) {
                        $foundOrder = $mo;
                        break;
                    }
                }
                if ($foundOrder) {
                    // 存在匹配的数据
                    $foundOrder->orderType= 1;
                    $foundOrder->score = $minusScore;
                    $foundOrder->scoreAfter = $targetUser->score;
                    $foundOrder->refer = 'order';
                    $foundOrder->actionUserId = $payload['userId'];
                    $foundOrder->actionUserName = $payload['userName'];
                    $foundOrder->save();
                }else{
                    $orderModel = new Order();
                    $data = [
                        'userName' => $targetUser->userName,
                        'userId' => $targetUser->id,
                        'actionUserName' => $payload['userName'],
                        'actionUserId' => $payload['userId'],
                        'type' => 2,
                        'orderType' => 1,
                        'refer' => 'order',
                        'score' => $minusScore,
                        'scoreAfter' => $targetUser->score
                    ];
                    $orderModel->save($data);
                }
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiResponse::json(500, '操作失败', $e);
        }

        return ApiResponse::json(200, 'succeed', null);
    }

    public function chiefExport(){
        //厨师导出当天用户所点的菜品
        $today = date('Y-m-d');
        $todayOrders = model('UserOrder')
            ->where('targetDate', '=', $today)
            ->select();
        return ApiResponse::json(200,'succeed',$todayOrders);
    }
    public  function  exportData(){
        $dateList = input('dateList/a'); // 获取dateList参数（转为数组）
        $userName = input('userName');
        if(!$dateList){
            return ApiResponse::json(200,'succeed','查询日期不能为空');
        }
        $where = [];
        if (!empty($userName)) {
            $where[] = ['userName','like', '%' . $userName . '%'];
        }
        $model = model('UserOrder');
//        var_dump($dateList);
        $list = $model->where($where)
            ->whereTime('targetDate','between', [$dateList[0], $dateList[1]])
            ->order('create_time', 'desc')->select();
        return ApiResponse::json(200,'succeed',$list);
    }
    //已下单列表
    public function buyList(){
        $params = request()->param();
        $userName = input('userName'); // 获取dishName参数
        $dateList = input('dateList/a'); // 获取dateList参数（转为数组）

        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);

        $orderModel = model('UserOrder');
        $where = [];
        if (!empty($userName)) {
            // 如果userName不为空，再判断是不是管理员，是则进行模糊匹配
            if ($payload['level']<=2) {
                $where[] = ['userName','like', '%' . $userName . '%'];
            }else{
                return ApiResponse::json(300,'您还不是管理员',null);
            }
        }else{
            if ($payload['level']>2){
                //为空并且等级是普通人，就用token里的信息来查
                $where[] = ['userName','like', '%' . $payload['userName'] . '%'];
            }
        }
        if(!$dateList){
            return ApiResponse::json(300,'查询日期不能为空',null);
        }
        $page = input('page');
        $pageSize = input('pageSize');
        $list = $orderModel->where($where)
            ->whereTime('targetDate','between', [$dateList[0], $dateList[1]])
            ->order('create_time', 'desc') // 按create_time字段倒序排序
            ->paginate($pageSize, false, ['page' => $page]);
        return ApiResponse::json(200,'succeed',$list);
    }
    public function deleteBuyOrder(){
        $params = request()->param();
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        $uid = $payload['userId'];
        // if($payload['level'] > 2){
        //     return ApiResponse::json(300,'您还不是管理员',null);
        // }

        $food = model('UserOrder');
        $targetFood = $food->where('id','=',$params['id'])->find();
        if (empty($targetFood)) {
            return ApiResponse::json(300,'订单不存在',null);
        }
        $gearModel = model('Gears');
        $gear = $gearModel::where('value', $targetFood->timeRange)->find();;

        $targetTime = $targetFood->targetDate.' '.$gear->ableEndTime.':00';
        // 获取当前时间注意使用 \DateTime 来引用全局 DateTime 类
        $currentDate = new \DateTime();
        // 解析给定的日期字符串
        $targetDate = \DateTime::createFromFormat('Y-m-d H:i:s', $targetTime);
        // 判断当前时间是否超过给定时间
        if ($currentDate > $targetDate) {
            return ApiResponse::json(300,'已过点餐截止时间',null);
        }

        if ($targetFood->userId != $uid && $payload['level'] > 2) {
            return ApiResponse::json(300,'您还不是管理员，不能删除他人订单',null);
        }
        $user = model('User')->where('id','=',$uid)->find();
        if (empty($user)) {
            return ApiResponse::json(300,'用户不存在',null);
        }
        $user->score += $targetFood->score;
        $user->save();
        $targetFood->delete();
        return ApiResponse::json(200,'操作成功',null);
    }

}
